package cn.com.chengmandian.bike.jobs;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.com.chengmandian.bike.constants.BikeConstants;
import cn.com.chengmandian.bike.constants.FaultBillInfoStatus;
import cn.com.chengmandian.bike.constants.FaultBillType;
import cn.com.chengmandian.bike.model.*;
import cn.com.chengmandian.bike.model.vo.RideOrderCountVo;
import cn.com.chengmandian.bike.service.*;
import cn.com.chengmandian.bike.utils.WxMiniService;
import cn.com.chengmandian.core.common.constants.CommonConstant;
import cn.com.chengmandian.core.redis.cache.AgentParamCacheService;
import cn.com.chengmandian.core.redis.service.RedisService;
import cn.com.chengmandian.core.web.pojo.AgentInfo;
import cn.com.chengmandian.core.web.pojo.BikeParam;
import cn.com.chengmandian.core.web.utils.LocalMapUtil;
import cn.com.chengmandian.service.bike.BikeCommonClient;
import cn.com.chengmandian.service.bike.constants.RideOrderStatusEnum;
import cn.com.chengmandian.service.bike.form.MessageAddForm;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.netflix.discovery.converters.Auto;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class OrderJob {
    @Autowired
    private IEbRideOrderService rideOrderService;

    @Autowired
    private IEbAgentInfoService agentInfoService;

    @Autowired
    private IEbMemberInfoService memberInfoService;

    @Autowired
    private WxMiniService wxMiniService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private AgentParamCacheService agentParamCacheService;

    @XxlJob("OrderInfoRefresh")
    public void refreshOrderInfo() {
        XxlJobHelper.log("OrderInfoRefresh start!");
        List<EbAgentInfo> agentInfoList = agentInfoService.list();
        for(EbAgentInfo agentInfo: agentInfoList) {
            AgentInfo agent = new AgentInfo();
            BeanUtils.copyProperties(agentInfo, agent);
            LocalMapUtil.setAgentInfo(agent);
            XxlJobHelper.log("处理品牌：" + agentInfo.getName());
            // 超二分钟未更新的骑行中订单
            List<EbRideOrder> orderList = rideOrderService.list(new LambdaQueryWrapper<EbRideOrder>()
                    .in(EbRideOrder::getStatus, RideOrderStatusEnum.RIDING.getCode(), RideOrderStatusEnum.PAUSE.getCode())
                    .lt(EbRideOrder::getModifyTime, DateUtil.offsetMinute(new Date(), -1))
                    .orderByDesc(EbRideOrder::getId));
            XxlJobHelper.log("发现长时间未刷新订单：" + orderList.size() + "个");
            for(EbRideOrder rideOrder : orderList){
                XxlJobHelper.log("刷新订单：" + rideOrder.getOrderNo());
                if (redisService.hasKey(BikeConstants.REDIS_LOCK_CMD_RIDE_ORDER_CLOSEING + rideOrder.getId())) {
                    XxlJobHelper.log("订单正在结算，本次更新跳过：" + rideOrder.getOrderNo());
                    continue;
                }
                rideOrder = rideOrderService.getById(rideOrder.getId());
                if (!rideOrder.getStatus().equals(RideOrderStatusEnum.RIDING.getCode()) && !rideOrder.getStatus().equals(RideOrderStatusEnum.PAUSE.getCode())) {
                    XxlJobHelper.log("订单已经不是骑行或暂停，本次更新跳过：" + rideOrder.getOrderNo());
                    continue;
                }
                // 订单结算
                if (rideOrder.getCloseTime() != null) {
                    if (DateUtil.between(rideOrder.getCloseTime(), new Date(), DateUnit.SECOND) > 60 * 5 ) {
                        XxlJobHelper.log("订单结算已超时（" + DateUtil.format(rideOrder.getCloseTime(), "yyyy-MM-dd HH:mm:ss") + "），取消结算信息：" + rideOrder.getOrderNo());
                        rideOrderService.cancelOrderSettleForClose(rideOrder.getId());
                    } else {
                        XxlJobHelper.log("订单已被结算" + DateUtil.format(rideOrder.getCloseTime(), "yyyy-MM-dd HH:mm:ss") + "，本次更新跳过：" + rideOrder.getOrderNo());
                        continue;
                    }
                }
                RideOrderCountVo rideOrderCountVo = rideOrderService.getOrderCount(rideOrder, rideOrder.getCloseTime() == null ? new Date() : rideOrder.getCloseTime(), true, false);

                rideOrderService.updateOrderRiding(rideOrder.getId(), rideOrderCountVo);
            }
        }
        XxlJobHelper.log("OrderInfoRefresh end!");
    }


//    /**
//     * 未支付订单通知
//     */
//    @XxlJob("OrderUnPayHandler")
//    public void OrderUnPayHandler() throws Exception {
//        XxlJobHelper.log("OrderUnPayHandler start!");
//        try {
//            String param = XxlJobHelper.getJobParam();
//            Integer noPaySeconds = StrUtil.isBlank(param) ? 7200 : Integer.parseInt(param);
//
//            //为了兼容mybats plus的 多租户模式
//            List<EbAgentInfo> agentInfos = agentInfoService.list();
//            for(EbAgentInfo agentInfo: agentInfos){
//                AgentInfo agent = new AgentInfo();
//                BeanUtils.copyProperties(agentInfo,agent);
//                LocalMapUtil.setAgentInfo(agent);
//                //1.获取未支付订单
//                List<EbRideOrder> orders = rideOrderService.listUnPayOrder(noPaySeconds);
//                //2.遍历 发推送信息
//                for(EbRideOrder order : orders){
//                    //redis key 配合查询订单的过期时间上限，达到幂等性
//                    String redisKey = "CMD:BIKE:ORDER:PUSH:" + order.getOrderNo();
//                    if(!redisService.setNx(redisKey,1,noPaySeconds)){
//                        continue;
//                    }
//                    XxlJobHelper.log("未支付订单:{}", JSONObject.toJSONString(order));
//                    EbRemindRule notifyRule = remindRuleService.getNotifyRule(agentInfo.getId(), CommonConstant.TWO);
//                    if (notifyRule == null || !notifyRule.getPushChannel().contains(CommonConstant.THREE.toString()) || notifyRule.getWxMiniTemplete() == null) {
//                        continue;
//                    }
//                    EbMemberInfo memberInfo = memberInfoService.getById(order.getMemberId());
//                    if(memberInfo.getOpenId()!=null){
//                        //发送微信小程序消息
//                        MessageAddForm messageAddForm = new MessageAddForm();
//                        messageAddForm.setMemberId(memberInfo.getId());
//                        messageAddForm.setOpenId(memberInfo.getOpenId());
//                        messageAddForm.setWxTemplateId(notifyRule.getWxMiniTemplete());
//                        messageAddForm.setOrderNo(order.getOrderNo());
//                        messageAddForm.setRentTime(DateUtil.formatDateTime(order.getCreateTime()));
//                        messageAddForm.setUsedTime(DateUtil.between(order.getOpenTime(),order.getCloseTime(), DateUnit.MINUTE)+"分钟");
//                        messageAddForm.setAmount(order.getMoney()+"元");
//                        commonClient.sendOrderUnpaidWx(agentInfo.getId(), messageAddForm);
//                    }
//                }
//            }
//        } catch (Exception e) {
//            XxlJobHelper.log(e);
//        }
//        XxlJobHelper.log("OrderUnPayHandler end!");
//    }
}
